<template>
    <div v-loading.body="loading">

        <div class="maincontent">
            <el-card class="box-card">
                <div class="breadcrumb" slot="header">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{name:'产品管理'}">商品管理</el-breadcrumb-item>
                        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                <div class="boxtitle">
                    <div class="title">
                        商品详情
                    </div>
                </div>
                <div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form label-width="120px">
                                <el-form-item label="商品名称">
                                    <el-input v-model="goodinfo.goods_name" :maxlength="23"></el-input>
                                </el-form-item>
                                <el-form-item label="商品颜色分类">
                                    <el-button type="primary" @click="Visibleaddoption=true"><i
                                            class="el-icon-plus"></i>添加分类
                                    </el-button>
                                    <div style="margin-top: 5px">

                                    </div>
                                    <el-tabs type="border-card" v-if="goodoption.length" closable
                                             @tab-remove="removeoption"  v-model="tapindex">
                                        
                                         
                                            <el-tab-pane v-for="(item,index) of goodoption" :label="item.option_name"
                                                         :name="String(index+1)" :key="String(index+1)" v-if="item.deleteflag=='0'">
                                                <el-row :gutter="20">
                                                    <el-col :span="8" style="width: 60px">
                                                        单价:
                                                    </el-col>
                                                    <el-col :span="16" style="text-align: left">
                                                        {{item.option_money}} 元
                                                    </el-col>

                                                </el-row>
                                                <el-row :gutter="20">
                                                    <el-col :span="8" style="width: 60px">
                                                        库存:
                                                    </el-col>
                                                    <el-col :span="16" style="text-align: left">
                                                        {{item.option_stock}} 件
                                                    </el-col>
                                                </el-row>
                                                <el-row :gutter="20">
                                                    <el-col style="text-align: right">

                                                        <el-button type="primary" @click="edioption(item,index)">编辑</el-button>
                                                    </el-col>
                                                </el-row>
                                            </el-tab-pane>
                                        
                                    </el-tabs>
                                </el-form-item>
                            </el-form>
                        </el-col>
                        <el-col :span="12">

                            <div>
                                <el-button type="primary" @click="imgfileinput">上传图片
                                    <input @change="changeimgurl" type="file" id="imgfile" style="display: none" accept="image/png,image/jpeg,image/jpg,image/webp" v-if="showimginput">
                                </el-button>

                            </div>
                            <div class="imglist">
                                <div class="imglistitem" v-for="(item,index) in goodinfo.goods_imgs" v-if="goodinfo.goods_imgs">
                                    <img :src="item">
                                    <i class="el-icon-circle-cross imgbtn" @click="remgoodimg(index)"></i>
                                </div>
                            </div>


                        </el-col>
                    </el-row>
                </div>

                <div class="boxtitle">
                    <div class="title">
                        商品介绍
                    </div>
                </div>
                <el-row style="z-index: 1">
                    <el-col :span="24" style="z-index: 1">
                        <div id="editorElem" ></div>
                    </el-col>
                    <el-col :span="24" style="text-align: right">
                        <el-button type="primary" @click="Visibleyulan=true" style="margin-top: 5px">预览</el-button>
                    </el-col>
                </el-row>

                <div style="margin-top: 30px;text-align: center">
                    <el-button type="primary" size="large" @click="submitupdate">保 存</el-button>
                </div>

            </el-card>
        </div>


        <el-dialog title="添加分类" :visible.sync="Visibleaddoption">
            <el-form :model="addoption" ref="optionfrom" label-width="80px" v-if="Visibleaddoption">
                <el-form-item label="分类名称" prop="option_name" :rules="[
      { required: true, message: '分类名称不能为空'}]">
                    <el-input v-model="addoption.option_name"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="option_money" :rules="[
      { required: true, message: '单价不能为空'},
      { type: 'number', message: '单价必须为数字值'}
    ]">
                    <el-input v-model.number="addoption.option_money"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="option_stock" :rules="[
      { required: true, message: '库存不能为空'},
      { type: 'number', message: '库存必须为数字值'}
    ]">
                    <el-input v-model.number="addoption.option_stock"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="Visibleaddoption = false">取 消</el-button>
                <el-button type="primary" @click="addoptionAction">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑分类" :visible.sync="Visibleedioption">
            <el-form :model="edioptions" ref="edioptionfrom" label-width="80px" v-if="Visibleedioption">
                <el-form-item label="分类名称" prop="option_name" :rules="[
      { required: true, message: '分类名称不能为空'}]">
                    <el-input v-model="edioptions.option_name"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="option_money" :rules="[
      { required: true, message: '单价不能为空'},
      { type: 'number', message: '单价必须为数字值'}
    ]">
                    <el-input v-model.number="edioptions.option_money"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="option_stock" :rules="[
      { required: true, message: '库存不能为空'},
      { type: 'number', message: '库存必须为数字值'}
    ]">
                    <el-input v-model.number="edioptions.option_stock"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="Visibleedioption = false">取 消</el-button>
                <el-button type="primary" @click="edioptionAction">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="剪切图片" :visible.sync="Visiblecutimg">
            <div class="wrapper" style="width: 100%;height: 300px">
                <vueCropper ref="cropper" :img="file_url" :info="true" :outputSize="cutimgoption.size"
                            :outputType="cutimgoption.outputType"
                            :fixed="cutimgoption.fixed"
                            :fixedNumber="cutimgoption.fixedNumber"
                            :canScale="cutimgoption.canScale"
                            :autoCrop="cutimgoption.autoCrop"
                            :autoCropWidth="cutimgoption.autoCropWidth"
                            :autoCropHeight="cutimgoption.autoCropHeight"
                >

                </vueCropper>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="Visiblecutimg = false">取 消</el-button>
                <el-button type="primary" @click="besurecut">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="Visibleyulan" top="4%">
            <div style="margin: 0 auto" class="phonebox">
                <div v-html="goodinfo.goods_html" class="cont">

                </div>
            </div>
        </el-dialog>




    </div>
</template>
<script type="text/ecmascript-6">
    import VueCropper from "vue-cropper";
    import API from "../API"
    import E from 'wangeditor';
    var editor=null;
    import merge from "../until/merge"
    import {
            mapState
    } from 'vuex';
    export default{
        components: {
            "VueCropper": VueCropper
        },
        computed: {
            ...mapState({
                user: state => state.user
            }),
        },
        data(){
            return{
                Visibleaddoption: false,
                Visiblecutimg: false,
                showimginput:true,
                Visibleyulan:false,
                Visibleedioption:false,
                goodinfo:{},
                tapindex:"1",
                edioptionsindex:null,
                addoption: {
                    option_name: "",
                    option_stock: "",
                    option_money: "",
                    deleteflag:"0",
                    updtype:"add",
                },
                edioptions:{
                    option_name: "",
                    option_stock: "",
                    option_money: "",
                },
                file_url: "",
                goodoption: [],
                editorContent:"",
                loading:false,
                cutimgoption: {
                    outputType: 'jpeg',
                    info: true,
                    size: 1,
                    fixed: true,
                    fixedNumber: [1, 1],
                    canScale: true,
                    autoCrop: true,
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 200,
                    autoCropHeight: 200,
                }

            }
        },
        methods:{

            initdata(){
                this.loading=true;
                API.searchProductDetail({
                    goods_id:this.$route.params.id
                }).then((res)=>{
                    var json=res.data;
                    if(json.message=="success"){
                        this.goodinfo=json.infomap;
                        this.goodoption=json.list;
                        editor.txt.html(this.goodinfo.goods_html);
                        this.goodoption.forEach((item)=>{
                            delete item["createtime"];
                            delete item["updtime"];
                            item.updtype="";

                        })
                    }else {
                        this.$message({
                            showClose: true,
                            message: '查询失败',
                            type: 'error'
                        });
                    }

                    this.loading=false;
                }).catch(()=>{
                    this.loading=false;
                })
            },
            remgoodimg(index){
                this.goodinfo.goods_imgs.splice(index,1);
            },
            removeoption(targetName){
                var index = Number(targetName);
                let option=this.goodoption[index-1];
                if (option.id){
                    option.deleteflag="1";
                    option.updtype="upd";
                }else {
                    this.goodoption.splice(index-1, 1);
                }

            },
            addoptionAction(){
                this.$refs.optionfrom.validate((valid) => {
                    if (!valid) {
                        this.$message({
                            showClose: true,
                            message: '请正确填写分类字段',
                            type: 'warning'
                        });
                    } else {
                        this.goodoption.push(this.addoption);
                        this.Visibleaddoption = false;
                        this.tapindex=String(this.goodoption.length)
                    }
                })
            },
            besurecut(){
                this.$refs.cropper.getCropData((data) => {
                    this.loading=true;
                    let _this=this;
                    API.uploadLunboImg({
                        imgString:data
                    }).then((res)=>{
                        _this.loading=false;
                        let json =res.data;
                        if(json.message=="success"){
                            if(_this.goodinfo.goods_imgs==""){
                                _this.goodinfo.goods_imgs=[json.path]
                            }else {
                                _this.goodinfo.goods_imgs.push(json.path);
                            }
                            _this.Visiblecutimg = false;
                        }else {
                            this.$message({
                                showClose: true,
                                message: '图片上传失败',
                                type: 'error'
                            });
                        }
                    }).catch(()=>{
                        this.loading=false;
                    });



                })
            },
            edioption(item,index){
                this.edioptions=merge({},this.edioptions,item);
                this.Visibleedioption=true;
                this.edioptionsindex=index;
            },
            edioptionAction(){
                this.$refs.edioptionfrom.validate((valid) => {
                    if (!valid) {
                        this.$message({
                            showClose: true,
                            message: '请正确填写分类字段',
                            type: 'warning'
                        });
                    } else {
                        let item=this.goodoption[this.edioptionsindex];
                        item.option_name=this.edioptions.option_name;
                        item.option_stock=this.edioptions.option_stock;
                        item.option_money=this.edioptions.option_money;
                        if(item.id){
                            item.updtype="upd";
                        }
                        this.Visibleedioption=false;
                    }
                });

            },
            imgfileinput(){
                document.getElementById("imgfile").click();
            },
            changeimgurl(){
                const reader = new FileReader();
                reader.readAsDataURL(document.getElementById("imgfile").files[0]);
                reader.onload = (e) => {
                    this.file_url = e.target.result;
                    this.Visiblecutimg = true;
                };
                this.showimginput=false;
                setTimeout(()=>{
                    this.showimginput=true;
                },200)
            },
            submitupdate(){
                if(this.goodinfo.goods_name==""){
                    this.$message({
                        showClose: true,
                        message: '请填写商品名称',
                        type: 'warning'
                    });
                    return
                }
                if(this.goodinfo.goods_imgs==""&&!this.goodinfo.goods_imgs.length){
                    this.$message({
                        showClose: true,
                        message: '请至少上传一张宣传图片',
                        type: 'warning'
                    });
                    return
                }
                if(!this.goodoption.length){
                    this.$message({
                        showClose: true,
                        message: '请至少添加一个商品分类',
                        type: 'warning'
                    });
                    return
                }
                if(this.goodinfo.goods_html==""){
                    this.$message({
                        showClose: true,
                        message: '请编辑商品介绍',
                        type: 'warning'
                    });
                    return
                }
                this.loading=true;
                API.updateProductByCode({
                    goods_id:this.goodinfo.goods_id,
                    goods_name:this.goodinfo.goods_name,
                    goods_imgs:JSON.stringify(this.goodinfo.goods_imgs),
                    goods_html:this.goodinfo.goods_html,
                    goodsoptionjson:JSON.stringify(this.goodoption)
                }).then((res)=>{
                    this.loading=false;
                    let json=res.data;
                    if(json.message=="success"){
                        this.$notify({
                            title: '成功',
                            message: '修改成功',
                            type: 'success'
                        });
                        window.history.go(-1);
                    }else {
                        this.$notify({
                            title: '失败',
                            message: '修改失败',
                            type: 'error'
                        });
                    }
                }).catch(()=>{
                    this.loading=false;
                })
            }
        },
        mounted() {
             editor = new E('#editorElem');
            editor.customConfig.onchange = (html) => {
                this.goodinfo.goods_html = html
            };
            editor.customConfig.uploadFileName = 'file';
            editor.customConfig.uploadImgServer = '/brand_service/uploadimg.action';
            editor.customConfig.uploadImgTimeout = 10000;
            editor.customConfig.uploadImgMaxLength = 3;
            if(this.user){
                editor.customConfig.uploadImgParams = {
                    store_id: this.user.sys_user_toshop  // 属性值会自动进行 encode ，此处无需 encode
                };
            }
           this.$watch("user",function (newval) {
              if(newval){
                  editor.customConfig.uploadImgParams = {
                      store_id: this.user.sys_user_toshop  // 属性值会自动进行 encode ，此处无需 encode
                  };
              }
           });
            editor.create();
            this.initdata();
        },
        watch: {
            Visibleaddoption(newval){
                if (!newval) {
                    this.addoption = {
                        option_name: "",
                        option_stock: "",
                        option_money: "",
                        deleteflag:"0",
                        updtype:"add",
                    };
                }
            },
            Visibleedioption(newval){
                if (!newval) {
                    this.edioptions = {
                        option_name: "",
                        option_stock: "",
                        option_money: "",
                    };
                }
            }
        }
    }
</script>
<style lang="less">
    @import "../css/addgood.less";
</style>